/**
 *  Copyright 26.08.2012 oliver.keusemann@googlemail.com
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package de.xelerity.geolessi.types.verbindung;

import java.util.Comparator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import de.xelerity.helper.StringFunktionen;

public class LinieComperator implements Comparator<Linie> {

	private String prepNo(String nu) {
		StringBuffer resultString = new StringBuffer();
		try {
			Pattern regex = Pattern.compile("([0-9]+)", Pattern.CASE_INSENSITIVE);
			Matcher regexMatcher = regex.matcher(nu == null ? "" : nu);
			while (regexMatcher.find()) {
				int len = regexMatcher.end() - regexMatcher.start();
				regexMatcher.appendReplacement(resultString, StringFunktionen.minLenRight("$1", 12 - len, ' '));
			}
			regexMatcher.appendTail(resultString);
			return resultString.toString();
		} catch (Throwable ex) {
			return nu;
		}
	}

	public int compare(Linie a, Linie b) {
		try {
			String A = "X";
			String N = prepNo(a.getNummer());

			if ((a.getLinienTyp() & Linie.LinienTyp_UBAHN) > 0L) {
				A = "A";
			}
			if ((a.getLinienTyp() & Linie.LinienTyp_SBAHN) > 0L) {
				A = "B";
			}
			if ((a.getLinienTyp() & Linie.LinienTyp_BUS) > 0L) {
				A = "C";
			}
			A = A + (a.getLinienTypAsString() + N);

			String B = "X";
			N = prepNo(b.getNummer());
			if ((b.getLinienTyp() & Linie.LinienTyp_UBAHN) > 0L) {
				B = "A";
			}
			if ((b.getLinienTyp() & Linie.LinienTyp_SBAHN) > 0L) {
				B = "B";
			}
			if ((b.getLinienTyp() & Linie.LinienTyp_BUS) > 0L) {
				B = "C";
			}
			B = B + (b.getLinienTypAsString() + N);

			return A.toLowerCase().compareTo(B.toLowerCase());
		} catch (Throwable e) {
			return 0;
		}
	}
}